<template>
  <el-row class="mainpage">
    <el-col class="sidebar" :span="1">
      <el-col :offset="8">
        <el-button
          type="text"
          icon="el-icon-plus"
          @click="dialogVisible = true"
        ></el-button>
      </el-col>
      <el-col :offset="8">
        <el-button
          type="text"
          icon="el-icon-refresh"
          @click="Test"
        ></el-button>
      </el-col>
    </el-col>

    <el-dialog
      title="添加好友"
      :visible.sync="dialogVisible"
      :modal-append-to-body="false"
      :before-close="handleClose"
      width="30%"
    >
      <span>好友的用户名:</span>
      <el-form
        ref="AddFriendForm"
        :model="AddFriendForm"
        :rules="AddFriend_rule"
      >
        <el-form-item prop="inputname">
          <el-input
            v-model="AddFriendForm.inputname"
            placeholder="请输入好友的用户名"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button type="warning" @click="DialogClose">关闭</el-button>
        <el-button type="primary" @click="AddFriend_Confirm">确定</el-button>
      </span>
    </el-dialog>
    <el-col class="centerbar" :span="6">
      <div class="mainbar">
        <el-container>
          <el-aside width="40px">
            <img :src="HeadPic" class="imgbox" />
          </el-aside>
          <el-container>
            <el-header>{{ nickname }}</el-header>
          </el-container>
        </el-container>
      </div>
      <router-view
        class="chatlist Rollbar"
        name="chatlist"
        @GetTitle="GetTitle"
        @GetUid="GetUid"
        :friends="chatlist_item"
      ></router-view>
    </el-col>

    <el-col class="chatitem" :span="17">
      <div class="chatbar" v-bind:class="rec_cb">
        <el-row type="flex" justify="center" v-if="messagename">
          <el-col :span="12" style="text-align: center">
            <span>正在与{{ messagename }}聊天</span>
          </el-col>
        </el-row>
      </div>
      <router-view
        class="chatmessage Rollbar"
        name="chatmessage"
        :chats="chat_array"
      ></router-view>
      <div id="chatarea" v-bind:class="rec_ca">
        <el-form
          label-width="auto"
          :model="TextForm"
          :rules="rules"
          ref="TextForm"
        >
          <el-container>
            <el-header class="toolbar" height="25px">
              <div></div>
            </el-header>
            <el-main class="TextArea Rollbar">
              <el-form-item prop="inputText">
                <el-col :span="24">
                  <el-input
                    label-width="auto"
                    clearable
                    v-model="TextForm.inputText"
                    placeholder="请输入内容(1-255字)"
                    type="textarea"
                    style="margin: 0 0 0 0"
                    :rows="11"
                    resize="none"
                    @keyup.shift.enter.native="SendMessage"
                    v-if="messagename"
                  ></el-input>
                </el-col>
              </el-form-item>
            </el-main>
            <el-footer height="30px" style="background-color: #ffffff">
              <el-col :offset="19">
                <el-button
                  size="mini"
                  type="success"
                  @click="SendMessage"
                  v-if="messagename"
                >
                  发送(shift+enter)
                </el-button>
              </el-col>
            </el-footer>
          </el-container>
        </el-form>
      </div>
    </el-col>
  </el-row>
</template>

<script>
import { mapState } from "vuex";

export default {
  data() {
    return {
      entermessage: true,
      HeadPic: require("../assets/logo.png"),
      nickname: "test",
      messagename: "",
      TextForm: {
        inputText: "",
        myuid: "",
        touid: "",
        token: "",
      },
      AddFriendForm: {
        inputname: "",
        uid: "",
        token: "",
      },
      dialogVisible: false,
      rules: {
        inputText: [
          { required: true, message: "请输入内容", trigger: "change" },
          { min: 1, max: 255, message: "内容在1-255字之间", trigger: "change" },
        ],
      },
      AddFriend_rule: {
        inputname: [
          { required: true, message: "请输入内容", trigger: "change" },
          { min: 1, max: 20, message: "内容在1-20字之间", trigger: "change" },
        ],
      },
      chat_array: [],
      chatlist_item:[],
      timer:''
    };
  },
  methods: {
    GetTitle(data) {
      this.messagename = data;
    },
    GetUid(data) {
      this.TextForm.touid = data;
      this.initchat()
    },
    DialogClose() {
      this.AddFriendForm.inputname = "";
      this.dialogVisible = false;
    },
    handleClose(done) {
      this.AddFriendForm.inputname = "";
      done();
    },
    Test(){
      this.Heartbeat()
      // console.log(this.chatlist_item)
      // console.log(typeof(this.chatlist_item))
    },
    Heartbeat() {
      console.log("Heartbeat at" + new Date())
      let HeartForm = {
        uid: this.useruid,
        token: this.usertoken,
      };
      this.$store
        .dispatch("Heartbt", HeartForm)
        .then((response) => {
          let code = response.data.code;
          if (code === 200) {
            this.chatlist_item =JSON.parse(response.data.data)
            this.$store.commit("Regtoken", response.data.message);
            if(this.TextForm.touid!="") this.initchat()
          } else if (code == 401) {
            this.$message.error("暂未登录或token已经过期");
            this.$router.push("/");
            return false;
          } else {
            this.$message.error("发送失败");
            return false;
          }
        })
        .catch(() => {});
    },
    AddFriend_Confirm() {
      this.AddFriendForm.token = this.usertoken;
      this.AddFriendForm.uid = this.useruid;
      this.$refs.AddFriendForm.validate((valid) => {
        if (valid) {
          this.$store
            .dispatch("AdF", this.AddFriendForm)
            .then((response) => {
              let code = response.data.code;
              console.log(code);
              if (code === 200) {
                this.DialogClose();
                this.Heartbeat();
                this.$store.commit("Regtoken", response.data.message);
              } else if (code === 401) {
                this.$message.error("暂未登录或token已经过期");
                this.$router.push("/");
                return false;
              } else if(code === 500){
                this.$message.error("该用户已在好友列表中");
              }  
              else {
                this.$message.error("用户名错误");
                return false;
              }
            })
            .catch(() => {});
        } else {
          this.$message.error("请确认表单无误");
          return false;
        }
      });
    },
    SendMessage() {
      this.TextForm.token = this.usertoken;
      this.TextForm.myuid = this.useruid;
      // console.log(this.TextForm)
      this.$refs.TextForm.validate((valid) => {
        if (valid) {
          this.$store
            .dispatch("Mess", this.TextForm)
            .then((response) => {
              let code = response.data.code;
              // console.log(code);
              if (code === 200) {
                this.Heartbeat()
                this.TextForm.inputText = "";
                this.$store.commit("Regtoken", response.data.message);
              } else if (code === 401) {
                this.$message.error("暂未登录或token已经过期");
                this.$router.push("/");
                return false;
              }
              else {
                this.$message.error("发送失败");
                return false;
              }
            })
            .catch(() => {});
        } else {
          this.$message.error("请确认表单无误");
          return false;
        }
      });
    },
    init(){
      let InitForm = {
        uid: this.useruid,
        token: this.usertoken,
      };
      this.$store
        .dispatch("Init", InitForm)
        .then((response) => {
          let code = response.data.code;
          if (code === 200) {
            this.HeadPic =response.data.data;
            this.nickname = response.data.message;
          } else if (code == 401) {
            this.$message.error("暂未登录或token已经过期");
            this.$router.push("/");
            return false;
          } else {
            this.$message.error("初始化失败");
            return false;
          }
        })
        .catch(() => {});
    },
    initchat(){
      let initForm = {
        myuid:this.useruid,
        touid:this.TextForm.touid,
        token:this.usertoken
      };
      this.$store
        .dispatch("Initchat", initForm)
        .then((response) => {
          let code = response.data.code;
          if (code === 200) {
            this.chat_array =JSON.parse(response.data.data)
            // console.log(this.chat_array)
            this.$store.commit("Regtoken", response.data.message);
          } else if (code == 401) {
            this.$message.error("暂未登录或token已经过期");
            this.$router.push("/");
            return false;
          } else {
            this.$message.error("初始化失败");
            return false;
          }
        })
        .catch(() => {});
    }
    // GetHeight(){
    //   let tmp = document.getElementById("chatarea")
    //   console.log(tmp.offsetHeight)
    //   this.TextboxHeight.height = tmp.offsetHeight - 50 +"px"
    // }
  },
  computed: {
    ...mapState({
      usertoken: (state) => state.session.token,
      useruid: (state) => state.session.uid,
    }),
    rec_cb: function () {
      return {
        chatbar_rec: this.entermessage,
      };
    },
    rec_ca: function () {
      return {
        chatarea_rec: this.entermessage,
      };
    },
  },
  created() {
    // this.$nextTick(()=>{
    //   window.addEventListener('resize',this.GetHeight)
    //   this.GetHeight();
    // })
  },
  mounted() {
    // console.log(this.$route.params.data)
    this.$router.push({
      name: "subview",
    });
    this.Heartbeat()
    this.init()
    this.timer=setInterval(this.Heartbeat,1000*30)
  },
  beforeDestroy(){
    clearInterval(this.timer)
  },
  watch: {},
};
</script>

<style scoped>
@import "../style/main.css";
</style>
